<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="流程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['web:erp:process:tbProcessDesign:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete({})"
          v-hasPermi="['web:erp:process:tbProcessDesign:remove']"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      tooltip-effect
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="流程名称" align="center" prop="name" show-overflow-tooltip />
      <el-table-column label="表单名称" align="center" prop="type" show-overflow-tooltip />
      <el-table-column label="最后修改人" align="center" prop="">
        <template #default="{ row }">
          <span>{{ row.updateBy ? row.updateBy : row.createBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" align="center" prop="">
        <template #default="{ row }">
          <span>{{ row.updateTime ? row.updateTime : row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="DataLine" @click="goSetFlow(scope.row)"
            >流程图
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['web:erp:process:tbProcessDesign:edit']"
          >
            修改
          </el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['web:erp:process:tbProcessDesign:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      v-model="open"
      :title="title"
      width="500px"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="表单名称" prop="type">
          <el-select :disabled="form.id" v-model="form.type" placeholder="请选择表单名称">
            <el-option
              v-for="item in flowTypeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
          <span class="text-sm text-red-500">同一表单类型只能创建一个流程。</span>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="5"
            maxlength="250"
            show-word-limit
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer text-center">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import {
    pageTbProcessDesign,
    getTbProcessDesignInfo,
    addTbProcessDesign,
    updateTbProcessDesign,
    delTbProcessDesign,
    disabledFlowType,
    businessTypeData,
  } from '@/api/flowable/process-list';
  import modal from '@/plugins/modal';
  import { ElMessageBox } from 'element-plus';

  const router = useRouter();
  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    name: null,
    type: null,
    remark: null,
  });
  const queryRef = ref(null);
  const list = ref([]);
  const open = ref(false);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '表单名称不能为空', trigger: 'change' }],
    remark: [{ required: true, message: '描述启用不能为空', trigger: 'blur' }],
  });
  const flowTypeOptions = ref([]);

  function getList() {
    loading.value = true;
    pageTbProcessDesign(pageParams.value, queryParams.value)
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function reset() {
    form.value = {
      name: null,
      type: null,
      remark: null,
    };
    formRef.value?.resetFields();
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }

  function handleAdd() {
    reset();
    title.value = '添加流程设计';
    disabledFlowType().then((res) => {
      res.data?.forEach((item) => {
        const idx = flowTypeOptions.value?.findIndex((f) => f.value === item);
        if (idx !== -1) flowTypeOptions.value[idx].disabled = true;
      });
      open.value = true;
    });
  }

  function handleUpdate(row) {
    reset();
    const _id = row?.id ?? ids.value[0];
    getTbProcessDesignInfo(_id).then((res) => {
      form.value = res.data;
      title.value = '修改流程设计';
      open.value = true;
    });
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.value.id) {
          updateTbProcessDesign(form.value).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addTbProcessDesign(form.value).then((res) => {
            modal.msgSuccess('新增成功');
            open.value = false;
            getList();
            ElMessageBox.confirm('是否前往设计流程图', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              distinguishCancelAndClose: true,
            })
              .then(() => {
                router.push({ name: 'Model', query: { id: res.data } });
              })
              .catch(() => {});
          });
        }
      }
    });
  }

  function handleDelete(row) {
    const _ids = row?.id ?? ids.value.join(',');
    modal
      .confirm('是否确认删除?')
      .then(() => {
        return delTbProcessDesign(_ids);
      })
      .then(() => {
        getList();
        modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  function goSetFlow(row) {
    router.push({ name: 'Model', query: { id: row.id } });
  }

  async function getFlowTypeOptions() {
    const res = await businessTypeData();
    flowTypeOptions.value = res.data;
  }

  getFlowTypeOptions();
  getList();
</script>
